/**
 * Created by rplees on 3/8/16.
 */
String.prototype.replaceAll = function(reallyDo, replaceWith, ignoreCase) {
    if (!RegExp.prototype.isPrototypeOf(reallyDo)) {
        return this.replace(new RegExp(reallyDo, (ignoreCase ? "gi": "g")), replaceWith);
    } else {
        return this.replace(reallyDo, replaceWith);
    }
}



/**
 * Created by Administrator on 13-12-20.
 */
const NullUtils = {
    NULL: "NULL",
    isNotNull: function(o) {
        return o != null && o != undefined;
    },
    isNull: function(o) {
        return !this.isNotNull(o);
    }
}

const JsonUtils = {
    encode(json){
        if (NullUtils.isNull(json)) {
            return '';
        }

        var tmps = [];
        for (var key in json) {
            tmps.push(key + '=' + json[key]);
        }

        return tmps.join('&');
    }
}

const StringUtils = {
    //字符串长度,中文算两个
    strlen(str){
      var len = 0;
      for (var i=0; i<str.length; i++) {
       var c = str.charCodeAt(i);
      //单字节加1
       if ((c >= 0x0001 && c <= 0x007e) || (0xff60<=c && c<=0xff9f)) {
         len++;
       }
       else {
        len+=2;
       }
      }
      return len;
    },

    isBlank: function(s) {
        if(!s) {
            return true;
        }

        if(s == "" || (s.match && s.match(/^\s+$/g))) {
            return true;
        }

        return false;
    },

    isNotBlank: function(s){
        return !this.isBlank(s);
    },

    equals: function(s1, s2) {
        return s1 == s2;
    },

    equalsIgnoreCase: function(s1, s2){
        if(s1 == s2) {
            return true;
        }

        if(NullUtils.isNull(s1) || NullUtils.isNull(s2)) {
            return false;
        }

        return s1.toLocaleUpperCase() == s2.toLocaleUpperCase();
    },

    subString: function(s, start, len) {
        if(this.isBlank(s)) {
            return s;
        }

        return s.substr(start, len);
    },
}

CollectionUtils = {
    isEmpty: function(o) {
        if(! o) return true;

        var list = null;
        if(o instanceof  Array) {
            list = o;
        } else if(o.list) {
            list = o.list;
        } else if(o.items) {
            list = o.items;
        }
        //后续继续

        if(!list || list.length < 1) {
            return true;
        }

        return false;
    },

    isNotEmpty: function(o) {
        return !this.isEmpty(o);
    },
    removeIndex: function(array,index) { // array.splice(index, 1)
        var pop = array.splice(index, 1);
        return pop;
    }
}

NumberUtils = {
    /**
     * 向上取整
     */
    ceil: function(s){
        var v = Math.ceil(s);
        if(isNaN(v)) {
            return -1;
        }

        return v;
    },

    toInt: function(s) {
        return parseInt(s);
    },

    isNumber: function(o) {
        if(o instanceof Number) {
            return true;
        }
        return this.toInt(o) == o
    },

    toLocaleString: function(num) {
        if(num < 1000) {
            return num + "";
        }

        var retV = "";
        var wasContinue = true;
        var tempV = 0;
        while(wasContinue == true) {
            tempV = num%1000;
            num = this.toInt(num/1000);
            wasContinue = num >= 1;

            if(wasContinue) {
                if(tempV < 10) {
                    tempV = "00" + tempV;
                }else if(tempV < 100) { //少于三位数 补0
                    tempV = "0" + tempV;
                }
            }
            retV = tempV + retV;

            if(wasContinue) {
                retV = "," + retV;
            }
        }

        return retV;
    },

    getNumberFromLocaleString: function(stringValue) {
        return this.toInt(stringValue.replaceAll(",", ""));
    }
}

BooleanUtils = {
    parseBooleanWithDefault: function(o, defaultValue) {
        if(o == null || o == undefined) {
            return defaultValue;
        }

        return this.parseBoolean(o);
    },
    parseBoolean: function(o) {
        if(o == null || o == undefined) {
            return false;
        }

        if(o instanceof  Number) {
            return o != 0;
        }

        if(o == "true" || o == "TRUE" || o == true)
            return true;

        return false;
    }
}

// 表单验证
const TextUtils = {

    isPhone: function(phone) {
        var myreg = /^\d{11}$/;
        if(!myreg.test(phone)) {
            return false;
        }

        return true;
    },
    /*
     * 是否邮件地址
     * */

    isEmail: function(email) {
        var res = email.match(/\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/);
        if (res !== null) {
            return res[0];
        }
        return false;
    },
    /**
     * 是否仅数字和字母
     * @param str
     * @param min 最小长度 默认0
     * @param max 最大长度 默认最大10000
     * @returns {boolean}
     */
    isNumberCharacter: function (str, min, max) {
        min = min || 1;
        max = max || 10000;
        var len = str.length;
        if (min > len || len > max) {
            return false;
        }
        var res = new RegExp(/^[a-z0-9]+$/i);
        return res.test(str);
    },

    /**
     * 是否URL格式
     * @param str
     * @returns {*}
     */
    isHttp: function(str) {
        var regHttp = /^https?:\/\/(([a-zA-Z0-9_-])+(\.)?)*(:\d+)?(\/((\.)?(\?)?=?&?[a-zA-Z0-9_-](\?)?)*)*$/i;
        var resRegHttp = str.match(regHttp);

        if (resRegHttp) {
            return resRegHttp[0];
        }
        return false;
    }
}

// 对Date的扩展，将 Date 转化为指定格式的String
// 月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符，
// 年(y)可以用 1-4 个占位符，毫秒(S)只能用 1 个占位符(是 1-3 位的数字)
// 例子：
// (new Date()).Format("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423
// (new Date()).Format("yyyy-M-d h:m:s.S")      ==> 2006-7-2 8:9:4.18
Date.prototype.format = function(fmt) { //author: meizz
    var o = {
        "M+" : this.getMonth()+1,                 //月份
        "d+" : this.getDate(),                    //日
        "h+" : this.getHours(),                   //小时
        "m+" : this.getMinutes(),                 //分
        "s+" : this.getSeconds(),                 //秒
        "q+" : Math.floor((this.getMonth()+3)/3), //季度
        "S"  : this.getMilliseconds()             //毫秒
    };
    if(/(y+)/.test(fmt))
        fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length));
    for(var k in o)
        if(new RegExp("("+ k +")").test(fmt))
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));
    return fmt;
}
const DateUtils = {
    //不可用
    format: function(dateTimeStamp){
        return DateUtils.formatDate(dateTimeStamp, "yyyy-MM-dd hh:mm:ss");
    },
    //不可用
    formatDate: function(dateTimeStamp, f){
      if(!dateTimeStamp){
        return "";
      }
        return new Date(dateTimeStamp).format(f);
    },
    //不可用
    formatDiff: function(dateTimeStamp){//FIXME:该函数是与当前时间比较,几个小时前\几天前格式化显示
        return new Date(dateTimeStamp).format("yyyy-MM-dd");
    },

    formatActivity: function(dateTimeStamp) {
      //dateTimeStamp 2017-03-31 03:22:11
      let date = this.getDate(dateTimeStamp);
      return  date.monthStr + "月" + date.day + "日" + date.hoursStr + ":" + date.minutesStr;
    },
    formatActivity1: function(dateTimeStamp) {
      //dateTimeStamp 2017-03-31 03:22:11
      let date = this.getDate(dateTimeStamp);
      return  date.yeahStr + "年" + date.monthStr + "月" + date.day + "日" + date.hoursStr + ":" + date.minutesStr;
    },
    formatHeartDate: function(dateTimeStamp) {
      //dateTimeStamp 2017-03-31 03:22:11
      let date = this.getDate(dateTimeStamp);
      return  date.yeahStr + "." + date.monthStr + "." + date.day + "   " + date.hoursStr + ":" + date.minutesStr;
    },
    formatHomeActivity: function(dateTimeStamp) {
      //dateTimeStamp 2017-03-31 03:22:11
      let date = this.getDate(dateTimeStamp);
      return  date.monthStr + "月" + date.day + "日 " + date.hoursStr + ":" + date.minutesStr;
    },
    formatOffocile: function(dateTimeStamp) {
      //dateTimeStamp 2017-03-31 03:22:11
      let date = this.getDate(dateTimeStamp);
      return  date.yeahStr + "."+date.monthStr + "." + date.day;
    },

    parseDate:function(date) {
      var isoExp, parts;
      isoExp = /^\s*(\d{4})-(\d\d)-(\d\d)\s(\d\d):(\d\d):(\d\d)\s*$/;
      try {
          parts = isoExp.exec(date);
      } catch(e) {
          return null;
      }
      if (parts) {
          date = new Date(parts[1], parts[2] - 1, parts[3], parts[4], parts[5], parts[6]);
      } else {
          return null;
      }
      return date;
    },

    getNow: function() {
      var now = new Date();
      var date = {};
      date.yeah = now.getFullYear();
      date.yeahStr = date.yeah;
      // date.monthStr = arr1[1];
      date.month = now.getMonth();
      date.monthStr = (date.month + 1) >= 10 ? (date.month + 1) : "0" + (date.month + 1);;
      date.day = now.getDate();
      date.dayStr = date.day >= 10 ? date.day : "0" + date.day;
      date.hours = now.getHours();
      date.hoursStr = date.hours >= 10 ? date.hours : "0" + date.hours;
      date.minutes = now.getMinutes();
      date.minutesStr = date.minutes >= 10 ? date.minutes : "0" + date.minutes;
      date.second = now.getSeconds();
      date.secondStr = date.second >= 10 ? date.second : "0" + date.second;
      return date;
    },

    getDate: function(dateTimeStamp) {
      //dateTimeStamp 2017-03-31 03:22:11  || 00:00:00
      if(dateTimeStamp == "" || dateTimeStamp == null) {
        dateTimeStamp = "0000-00-00 00:00:00";
      }
      let rightPart = "";
      let arr1 = dateTimeStamp.split("-");
      var date = {};
      var time = 0;
      //2017-03-31 03:22:11
      if(arr1.length == 3) {
        date.yeah = parseInt(arr1[0]);
        date.yeahStr = date.yeah;
        date.month = parseInt(arr1[1] - 1);
        date.monthStr = (date.month + 1) >= 10 ? (date.month + 1) : "0" + (date.month + 1);
        let arr2 = arr1[2].split(" ");
        date.day = parseInt(arr2[0]);
        date.dayStr = date.day >= 10 ? date.day : "0" + date.day;
        rightPart = arr2[1];
      }
      //00:00:00
      else {
        rightPart = dateTimeStamp;
      }
      let arr3 = rightPart.split(":");
      date.hours = parseInt(arr3[0]);
      date.hoursStr = date.hours >= 10 ? date.hours : "0" + date.hours;
      date.minutes = parseInt(arr3[1]);
      date.minutesStr = date.minutes >= 10 ? date.minutes : "0" + date.minutes;
      date.second = parseInt(arr3[2]);
      date.secondStr = date.second >= 10 ? date.second : "0" + date.second;

      return date;
    },

    compareDate: function(aDate, bDate) {
      if(aDate.yeah != bDate.yeah) {
        return aDate.yeah - bDate.yeah;
      }
      else if (aDate.month != bDate.month) {
        return aDate.month - bDate.month;
      }
      else if (aDate.day != bDate.day) {
        return aDate.day - bDate.day;
      }
      else if (aDate.hours != bDate.hours) {
        return aDate.hours - bDate.hours;
      }
      else if (aDate.minutes != bDate.minutes) {
        return aDate.minutes - bDate.minutes;
      }
      return aDate.second - bDate.second;
    },

    transIntToStr: function(num) {
      if(num < 10) {
        return "0" + num;
      }
      return num;
    },

    //hh:mm 今天|昨天|yyyy-MM-dd
    formatDate2: function(dateTimeStamp, needYear = true){
      if(dateTimeStamp == null || dateTimeStamp == "") {
        return "";
      }
      let dateNow = new Date();
      let date = this.getDate(dateTimeStamp)
      if(date.yeah == dateNow.getFullYear() && date.month == dateNow.getMonth()) {
        if(dateNow.getDate() - date.day == 1) {
          return date.hoursStr + ":" + date.minutesStr + " 昨天";
        }
        else if(dateNow.getDate() == date.day) {
          return date.hoursStr + ":" + date.minutesStr + " 今天";
        }
      }
      return this.formatDateFull(date, needYear);
    },
    formatDate3: function(dateTimeStamp, needYear = true){
      if(dateTimeStamp == null || dateTimeStamp == "") {
        return "";
      }
      let dateNow = new Date();
      let date = this.getDate(dateTimeStamp)
      if(date.yeah == dateNow.getFullYear() && date.month == dateNow.getMonth()) {
        if(dateNow.getDate() - date.day == 1) {
          return date.hoursStr + ":" + date.minutesStr + " 昨天";
        }
        else if(dateNow.getDate() == date.day) {
          return date.hoursStr + ":" + date.minutesStr + " 今天";
        }
      }
      return this.formatDateFull1(date, needYear);
    },

    formatDateMnD: function(dateTimeStamp) {
      let date = this.getDate(dateTimeStamp)
      return date.hoursStr + ":" + date.minutesStr;
    },
    formatDateMnD1: function(dateTimeStamp) {
      let date = this.getDate(dateTimeStamp)
      const nowDate = new Date();
      if (date.day < nowDate.getDate()) {
        return date.yeahStr+'/'+date.monthStr+'/'+date.dayStr;
      }else{
        return date.hoursStr + ":" + date.minutesStr;
      }
      
    },

    formatDateFull: function(date, needYear) {
      let str = "";
      if(needYear === true) {
        str += date.yeahStr + "-";
      }
      return str + date.monthStr + "-" + date.dayStr + " " + date.hoursStr + ":" + date.minutesStr;
    },
    formatDateFull1: function(date, needYear) {
      let str = "";
      if(needYear === true) {
        str += date.yeahStr + "-";
      }
      return str + date.monthStr + "-" + date.dayStr;
    },

    //dateString : yyyy-MM-dd hh:mm:ss
    formatDiffFromServerTime: function(dateString) { //和服务器返回的时间对比出 小时|天|月
      if(dateString == "" || !dateString) {
        return "无时间";
      }
      const serverDate = this.getDate(dateString);
      // console.log("formatDiffFromServerTime", dateString, serverDate);
      // const serverTime = serverDate.getTime().toString();

      const nowDate = new Date();
      // console.log("formatDiffFromServerTime", nowDate);
      // const nowTime = nowDate.getTime().toString();
      // console.log("serverDate", );
      var resultStr = "";
      if(serverDate.yeah < nowDate.getFullYear()) {
        resultStr = nowDate.getFullYear() - serverDate.yeah + " 年前";
      }
      else if(serverDate.month < nowDate.getMonth()) {
        resultStr = nowDate.getMonth() - serverDate.month + " 月前";
      }
      else if(serverDate.day < nowDate.getDate()) {
        resultStr = nowDate.getDate() - serverDate.day + " 天前";
      }
      else if(serverDate.hours < nowDate.getHours()) {
        resultStr = nowDate.getHours() - serverDate.hours + " 小时前";
      }
      else if(serverDate.minutes < nowDate.getMinutes()) {
        resultStr = nowDate.getMinutes() - serverDate.minutes + " 分钟前";
      }
      else {
        resultStr = "刚刚";
      }
      return resultStr;
    },

    getWeekName: function(week) {
      let str = "错误";
      switch (week) {
        case 1:
          str = "星期一";
          break;
        case 2:
          str = "星期二";
          break;
        case 3:
          str = "星期三";
          break;
        case 4:
          str = "星期四";
          break;
        case 5:
          str = "星期五";
          break;
        case 6:
          str = "星期六";
          break;
        case 0:
          str = "星期日";
          break;
      }
      return str;
    },
}

const ObjUtils = {
    toString : function(o) {
        if(NullUtils.isNull(o)) {
            return "null";
        }

        if((typeof o) == "string") {
            return o;
        } else if((typeof o) == "object") {
            var s = "";
            for(var idx in o) {
                s += idx + "=" + ObjUtils.toString(o[idx]) + ",";
            }

            return s;
        } else if((typeof o) == "funtion") {
            var s = "fun[" + o +"]";
        } else {
            return o;
        }
    },
    copy: function(object) {
      return JSON.parse(JSON.stringify(object));
    },

    dataKeyArr: ["cardno", "lovequestion_id", "lovemsg_id", "landmark_id", "comment_id",
      "slide_id", "activity_id", "post_id", "expert_id", "news_id", "chatgroup_id", "board_id", "by_user_id",
      "msguser_id", "item_id", ],

    concatArrayNoRepeat: function(preArr, newArr, dataKey) {
      let exist = false;
      let tempPreArr = preArr.concat();
      for (var i = 0; i < newArr.length; i++) {
        exist = false;
        for (var j = 0; j < tempPreArr.length; j++) {
          if(dataKey === undefined || tempPreArr[j][dataKey] === undefined) {
            console.warn("dataKey does not existed");
            for (var k = 0; k < ObjUtils.dataKeyArr.length; k++) {
              if(tempPreArr[j][ObjUtils.dataKeyArr[k]] != undefined) {
                dataKey = ObjUtils.dataKeyArr[k];
                console.info("dataKey may be " + dataKey);
                console.log("dataKey data", tempPreArr[j])
                break;
              }
            }
          }
          if(dataKey === undefined) {
            // console.log("dataKey error:", tempPreArr[j])
          }
          if(dataKey && tempPreArr[j][dataKey] === newArr[i][dataKey]) {
            tempPreArr[j] = newArr[i];
            exist = true;
            break;
          }
        }
        if(exist === false) {
          tempPreArr.push(newArr[i]);
        }
      }
      return tempPreArr;
    },
}

const pattP=/<p["& ./=0-9a-zA-Z:(,);!\-\u4e00-\u9fa5]*>/g;
const pattSpan=/<span["& ./=0-9a-zA-Z:(,);!\-\u4e00-\u9fa5]*>/g;
const pattStrong=/<strong["& ./=0-9a-zA-Z:(,);!\-\u4e00-\u9fa5]*>/g;
const pattTable=/<table["& ./=0-9a-zA-Z:(,);!\-\u4e00-\u9fa5]*>/g;
const pattTd=/<td["& ./=0-9a-zA-Z:(,);!\-\u4e00-\u9fa5]*>/g;
const pattTr=/<tr["& ./=0-9a-zA-Z:(,);!\-\u4e00-\u9fa5]*>/g;
const pattBody=/<tbody["& ./=0-9a-zA-Z:(,);!\-\u4e00-\u9fa5]*>/g;
const pattBr=/<br["& ./=0-9a-zA-Z:(,);!\-\u4e00-\u9fa5]*>/g;
const pattDiv=/<div["& ./=0-9a-zA-Z:(,);!\-\u4e00-\u9fa5]*>/g;
const pattImg=/<img["& ./=0-9a-zA-Z:(,);!\-\u4e00-\u9fa5]*>/g;
const pattP2=/<\/[a-zA-Z]+>/g;
const pattPHuanhuang=/<\/span><\/div>/g;
const pattfontSize=/font-size\s*:\s*[0-9]+/g;
const pattNum=/[0-9]+/g;
const pattSpace=/[&nbsp;]+/g;
const HtmlUtils = {
  //文章内容去html
  contentFormat : function(param) {
    return param.replace(pattP, "").replace(pattSpan, "").replace(pattStrong, "")
      .replace(pattTable, "").replace(pattTd, "").replace(pattTr, "").replace(pattBody, "").replace(pattBr, "")
      .replace(pattDiv, "").replace(pattImg, "").replace(pattPHuanhuang, "\n")
      .replace(pattP2, "\n").replace(pattSpace, "");
  },

  contentFormatImg : function(param) {
    if(!param){
      return "";
    }
    return param.replace(/(<img)["&./ =0-9a-zA-Z:(,);!\-\u4e00-\u9fa5]*( src="[:"&./=0-9a-zA-Z:(,);!\-\u4e00-\u9fa5]*" )["&./ =0-9a-zA-Z:(,);!\-\u4e00-\u9fa5]*(>)/g,"$1$2$3");
  },

  contentFontSizeScale:function(param, changeSize) {
    let matchResult = param.match(pattfontSize);
    let fontStr = "";
    let sizeNum = 0;
    let sizeResult = null;
    let newFontStr = null;
    let regExp = null;
    let returnStr = param;
    for (var i = 0; i < matchResult.length; i++) {
      fontStr = matchResult[i];
      sizeResult = fontStr.match(pattNum);
      sizeNum = parseInt(sizeResult[0]) + changeSize;
      newFontStr = fontStr.replace(pattNum, sizeNum);
      regExp = new RegExp(fontStr, "gim");
      returnStr = returnStr.replace(regExp, newFontStr);
    }
    return returnStr;
  },

  contentFormatFontSize : function(param, size) {
    var str = "font-size: " + size;
    var returnStr = param.replace(/font-size\s*:\s*[0-9]*/g, str);
    return returnStr;
  },

  getHtmlWeb:function(content, width) {
    return {html:`<!doctype html>
        <html>
        <head>
            <meta charset="utf-8">
            <style type="text/css">
                body {
                    overflow-x:hidden;
                    overflow-y:hidden;
                    pading:0;
                    margin:0;
                    }
                img{
                  max-width:100%
                }

            </style>
        </head>
        <body style="width: ` + width + `px;">` + content +
        `<script type="text/javascript">
            function awaitPostMessage() {
              var isReactNativePostMessageReady = !!window.originalPostMessage;
              var queue = [];
              var currentPostMessageFn = function store(message) {
                if (queue.length > 100) queue.shift();
                queue.push(message);
              };
              if (!isReactNativePostMessageReady) {
                var originalPostMessage = window.postMessage;
                Object.defineProperty(window, 'postMessage', {
                  configurable: true,
                  enumerable: true,
                  get: function () {
                    return currentPostMessageFn;
                  },
                  set: function (fn) {
                    currentPostMessageFn = fn;
                    isReactNativePostMessageReady = true;
                    setTimeout(sendQueue, 0);
                  }
                });
                window.postMessage.toString = function () {
                  return String(originalPostMessage);
                };
              }

              function sendQueue() {
                while (queue.length > 0) window.postMessage(queue.shift());
              }
            }
            awaitPostMessage();
            var isLoad = false;
            window.onload = function(){
            window.location.hash = 1;document.title = document.body.clientHeight;
            document.body.onclick=function(event){
              console.log(event.target);
              if(event.target && event.target.tagName == "IMG") {
                window.postMessage(event.target.src + "#1#" + event.target.width + "#1#" + event.target.height);
              }
            }
        }
        </script>
        </body>
      </html>`}
  },
}

exports.StringUtils = StringUtils;
exports.BooleanUtils = BooleanUtils;
exports.JsonUtils = JsonUtils;
exports.CollectionUtils = CollectionUtils;
exports.NullUtils = NullUtils;
exports.NumberUtils = NumberUtils;
exports.StringUtils = StringUtils;
exports.TextUtils = TextUtils;
exports.DateUtils = DateUtils;
exports.ObjUtils = ObjUtils;
exports.HtmlUtils = HtmlUtils;
